#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月19日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(current_dir,'../../'))

import logging

from base.time_method import myTimeMethod

from base.retail_datas import RetailDatas
myRetailDatas = RetailDatas()

from base.zhimind_datas import ZhimindDatas
myZhimindDatas = ZhimindDatas()

import openpyxl
logger = logging.getLogger('base.export_month_data_by_temp')




class ExportMonthData(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
    def analyze_template_file(self,rule=None,comp_group=None,temp_file=None,export_path=None,mail_to_list=None):
        if rule==None and (comp_group==None or temp_file==None):
            logger.error('Please Input Rule or (CompGroup and tempFile)')
            sys.exit(0)
        elif rule!=None:
            if comp_group==None:
                comp_group = myLocalConfig.rules[rule]['comp_group']
            if temp_file==None:
                temp_file = myLocalConfig.rules[rule]['template_file']
            if export_path==None:
                export_path = myLocalConfig.rules[rule]['export_path']
            if mail_to_list==None:
                mail_to_list =  myLocalConfig.rules[rule]['mail_to_list']
        if re.search('common/month_report_template_1',temp_file):
            self.analyze_template_file_month_report_template(temp_file, comp_group, day, export_path)
        
    def analyze_template_file_month_report_template(self,temp_file,comp_group,day=None,export_path=''):
        #前天
        last_day,last_day = myTimeMethod.get_last_st_et_by_timeType(day, timeType='day')
        #last day 本月
        month_st,month_et = myTimeMethod.get_st_et_by_timeType(last_day, timeType='month',range='end')
        #last day 上月
        last_month_st,last_month_et = myTimeMethod.get_last_st_et_by_timeType(month_st, timeType='month',range='start')
        
        
        logger.info( 'last_day_month st et:%s %s'%(month_st,month_et))
        logger.info( 'last_day_last_month st et:%s %s'%(last_month_st,last_month_et))
        #sys.exit()
        
        wb =        openpyxl.load_workbook(temp_file)  
        comp_id = myRetailDatas.get_comp_id(comp_group=comp_group)
        comp_name = myRetailDatas.get_comp_name(shop_group=comp_group)
        logger.info('Start Comp : %s'%comp_name)
        for sheet_name in wb.get_sheet_names():
            logger.debug('Start Sheet : %s'%sheet_name)
            ws = wb.get_sheet_by_name(sheet_name)  
            if sheet_name == u'核心数据':
                start_col = 0
                start_row = 4
                ws.cell(row=1,column=1).value = '门店WIFI客流数据表（%s年%s月）'%(month_st[:4],month_st[5:7])
            elif sheet_name == u'门店数据':
                start_col = 0
                start_row = 4
                ws.cell(row=1,column=1).value = '门店WIFI客流数据报表（%s年%s月）'%(month_st[:4],month_st[5:7])
            else:continue
            
            ws.cell(row=2,column=start_col+13).value = '%s月进店次数'%(int(month_st[5:7]))
            ws.cell(row=2,column=start_col+17).value = '%s月进店情况'%(int(month_st[5:7]))
            
            ws.cell(row=3,column=start_col+5).value = '%s月进店量'%(int(last_month_st[5:7]))
            ws.cell(row=3,column=start_col+6).value = '%s月进店量'%(int(month_st[5:7]))
            ws.cell(row=3,column=start_col+8).value = '%s月进店量'%(int(last_month_st[5:7]))
            ws.cell(row=3,column=start_col+9).value = '%s月进店量'%(int(month_st[5:7]))
            ws.cell(row=3,column=start_col+11).value = '%s月进店量'%(int(month_st[5:7]))
            
            groups = myRetailDatas.get_groups_by_comp(comp_group=comp_group)
            groupInfos = myRetailDatas.get_groups_info(groups=groups)
            
            #上月入店量
            customer_last_month_count_datas = myZhimindDatas.get_customer_count(groups=groups, startTime=last_month_st, endTime=last_month_et)
            
            #本月入店量
            customer_this_month_count_datas = myZhimindDatas.get_customer_count(groups=groups, startTime=month_st, endTime=month_et)
            
            #有效顾客上月入店量
            u_customer_last_month_count_datas = myZhimindDatas.get_customer_count(groups=groups, startTime=last_month_st, endTime=last_month_et,customerType='deep')
            
            #有效顾客本月入店量
            u_customer_this_month_count_datas = myZhimindDatas.get_customer_count(groups=groups, startTime=month_st, endTime=month_et,customerType='deep')
            
            #无效顾客 本月入店量
            #n_customer_this_month_count_datas = myZhimindDatas.get_customer_count(groups=groups, startTime=month_st, endTime=month_et,customerType='jump')
            
            
            #本月进店情况 工作日入店量 Q(17)
            customer_this_month_count_weekday_datas = myZhimindDatas.get_customer_count(groups=groups, startTime=month_st, endTime=month_et,timeType='weekday')
            #本月入店情况  周末入店量 R(18)
            customer_this_month_count_weekend_datas = myZhimindDatas.get_customer_count(groups=groups, startTime=month_st, endTime=month_et,timeType='weekend')
            
            
            for group,groupInfo in groupInfos.iteritems():
                start_row+=1
                col = start_col
                group_name = groupInfo['name']
                province = groupInfo['province']
                city = groupInfo['city']
                dist = groupInfo['dist']

                #省 A(1)
                col+=1
                ws.cell(row=start_row,column=col).value = province
                #市 B(2)
                col+=1
                ws.cell(row=start_row,column=col).value = city
                #区 C(3)
                col+=1
                ws.cell(row=start_row,column=col).value = dist
                #门店 D(4)
                col+=1
                ws.cell(row=start_row,column=col).value = group_name
                #上个月入店量 E(5)
                col+=1
                ws.cell(row=start_row,column=col).value = customer_last_month_count_datas[int(group)]
                #本月入店量 F(6)
                col+=1
                ws.cell(row=start_row,column=col).value = customer_this_month_count_datas[int(group)]
                #月入店量环比 G(7) = (F-E)/E
                col+=1
                
                ws.cell(row=start_row,column=col).value = "=(F%s-E%s)/E%s"%(start_row,start_row,start_row)
                #有效顾客 上个月入店量 where dur>5min H(8)
                col+=1
                ws.cell(row=start_row,column=col).value = u_customer_last_month_count_datas[int(group)]
                #有效顾客 本月入店量 where dur>5min I(9)
                col+=1
                ws.cell(row=start_row,column=col).value = u_customer_this_month_count_datas[int(group)]
                #有效顾客 月入店环比 J(10) = (I-H)/I
                col+=1
                ws.cell(row=start_row,column=col).value = "=(I%s-H%s)/I%s"%(start_row,start_row,start_row)
                #无效顾客 本月入店量 where dur<=5min K(11)
                col+=1
                #ws.cell(row=start_row,column=col).value = n_customer_this_month_count_datas[int(group)]
                ws.cell(row=start_row,column=col).value = "=(F%s-I%s)"%(start_row,start_row)
                #无效顾客 占比 L(12) = K/F
                col+=1
                ws.cell(row=start_row,column=col).value = "=K%s/F%s"%(start_row,start_row)
                #本月进店次数 M(13) - P(16)
                #本月进店次数
                freqTypes = {'1':'1:1','2':'2:2','3':'3:5','4':'6:99'}
                customer_visit_freq_datas = myZhimindDatas.get_visit_freq( groups=[group], startTime=month_st, endTime=month_et, freqTypes=freqTypes)
            
                freqTypeKeys = freqTypes.keys()
                freqTypeKeys.sort()
                for freqType in freqTypeKeys:
                    col+=1
                    ws.cell(row=start_row,column=col).value = customer_visit_freq_datas[freqType]
                #本月进店情况 工作日入店量 Q(17)
                col+=1
                ws.cell(row=start_row,column=col).value = customer_this_month_count_weekday_datas[int(group)]
                #本月入店情况  周末入店量 R(18)
                col+=1
                ws.cell(row=start_row,column=col).value = customer_this_month_count_weekend_datas[int(group)]
        export_file = os.path.join(export_path,u'月报表.%s.%s.csv'%(comp_name,month_st[:7]))
        wb.save(export_file) 
if __name__ == '__main__':
    import argparse,re,datetime,time
    
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--day',metavar=u"day",default=None)
    parser.add_argument('--rule',metavar=u"rule",default=None)
    parser.add_argument('--comp_group',metavar=u"comp_group",default=None)
    parser.add_argument('--temp',metavar=u"xlsx temp",default=None)
    parser.add_argument('--export_path',metavar=u"xlsx temp",default=None)
    parser.add_argument('--mail_to_list',metavar=u"xlsx temp",default=None)
    args = parser.parse_args()
    
    day = args.day
    rule = args.rule
    comp_group = args.comp_group
    temp_file = args.temp
    export_path = args.export_path
    mail_to_list = args.mail_to_list
    from localConfig import LocalConfig
    myLocalConfig = LocalConfig()
    if day==None:
        #day = (datetime.date.today()-datetime.timedelta(1)).strftime("%Y-%m-%d")
        day = datetime.date.today().strftime("%Y-%m-%d")
    yday = (datetime.date(int(day[:4]),int(day[5:7]),int(day[8:10]))-datetime.timedelta(1)).strftime("%Y-%m-%d")
    
    myExportMonthData = ExportMonthData()
    myExportMonthData.analyze_template_file(rule=rule, comp_group=comp_group, temp_file=temp_file, export_path=export_path, mail_to_list=mail_to_list)

    
    
    
    